package com.example.common.exception;

import com.example.common.dto.JsonResult;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class CommonExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public JsonResult<Object> businessExceptionHandler(BusinessException e) {
        return new JsonResult<>(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public JsonResult<Object> exceptionHandler(BindException e) {

        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        Object[] arguments = objectError.getArguments();
        String code = JsonResult.CODE_ERROR + "_" + arguments[0];
        String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();

        return new JsonResult<>(code, message);
    }

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public JsonResult<Object> exceptionHandler(Throwable e) {

        e.printStackTrace();

        return new JsonResult<>(JsonResult.CODE_ERROR, e.getMessage());
    }

}
